import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ApplicationRecordService} from '../../service/application-record.service';
import {SharedModule} from '../shared.module';
import {ApplicationRecordForm} from '../../types/req/ApplicationRecordForm';
import {MODAL_WIDTH} from '../../const'
import {EnterpriseSelectorComponent} from '../enterprise/enterprise-selector.component';
import {JobDescriptionSelectorComponent} from '../job-description/job-description-selector.component';
import {CandidateSelectorComponent} from '../candidate/candidate-selector.component';

@Component({
  selector: 'application-record-add',
  imports: [
    EnterpriseSelectorComponent,
    JobDescriptionSelectorComponent,
    CandidateSelectorComponent,
    SharedModule
  ],
  templateUrl: './application-record-add.component.html',
  standalone: true
})
export class ApplicationRecordAddComponent implements OnInit {
  applicationRecordToSave:ApplicationRecordForm = {};
  applicationRecordForm!: FormGroup;
  isVisible: boolean = false
  saveLoading: boolean = false
  title: string = '新增应聘申请'
  modalWidth: string = MODAL_WIDTH

  @ViewChild(EnterpriseSelectorComponent, { static: false }) enterpriseSelectorComponent!: EnterpriseSelectorComponent;
  @ViewChild(JobDescriptionSelectorComponent, { static: false }) jobDescriptionSelectorComponent!: JobDescriptionSelectorComponent;
  @ViewChild(CandidateSelectorComponent, { static: false }) candidateSelectorComponent!: CandidateSelectorComponent;

  @Output() addedEvent = new EventEmitter<boolean>();

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private applicationRecordService: ApplicationRecordService
  ) {}

  ngOnInit(): void {
    this.applicationRecordForm = this.fb.group({
      enterpriseId: [0],
      enterpriseName: ['', [Validators.required]],
      jobDescriptionId: [0],
      jobDescriptionName: ['', [Validators.required]],
      candidateId: [0],
      candidateName: ['', [Validators.required]],
      status: [undefined, [Validators.required]],
    })
  }

  onSave() {
    try {
      this.saveLoading = true
      for (const i in this.applicationRecordForm.controls) {
        this.applicationRecordForm.controls[i].markAsDirty();
        this.applicationRecordForm.controls[i].updateValueAndValidity();
      }
      if (!this.applicationRecordForm.valid) {
        this.saveLoading = false
        return
      }
      this.applicationRecordService.save(Object.assign(this.applicationRecordToSave, this.applicationRecordForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          this.message.success("保存成功")
          this.onBack(true)
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onReset() {
    this.title = '新增应聘申请'.slice()
    this.applicationRecordForm.reset()
  }

  onBack(addedFlag=false) {
    this.isVisible = false
    this.addedEvent.emit(addedFlag);
  }

  display(id: number) {
    this.isVisible = true
    if (id) {
      this.title = '修改应聘申请'
      this.saveLoading = true
      this.applicationRecordService.findById(id).subscribe({
        next: (resp) => {
          if (resp && resp.code === 1 && resp.data) {
            this.applicationRecordToSave = resp.data
            this.applicationRecordForm.patchValue(this.applicationRecordToSave);
          }
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } else {
      this.onReset()
    }
  }

  findEnterprise() {
    this.enterpriseSelectorComponent.display()
  }

  handleEnterpriseSelectedEvent(selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) {
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      this.applicationRecordForm.patchValue(selectedEnterprise);
    }
  }

  findJobDescription() {
    this.jobDescriptionSelectorComponent.display()
  }

  handleJobDescriptionSelectedEvent(selectedJobDescription: { jobDescriptionId?: number; jobDescriptionName?: string; }) {
    if (selectedJobDescription && 'jobDescriptionId' in selectedJobDescription) {
      this.applicationRecordForm.patchValue(selectedJobDescription);
    }
  }

  findCandidate() {
    this.candidateSelectorComponent.display()
  }

  handleCandidateSelectedEvent(selectedCandidate: { candidateId?: number; candidateName?: string; }) {
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      this.applicationRecordForm.patchValue(selectedCandidate);
    }
  }
}
